<?php
namespace Handlers;

class ExampleHandler extends Handler
{
    public $fields = [
        'id' => 'int',
        'content' => 'json', 
        'changed_at' => 'datetime',
        'category_id' => 'int'
    ];

    public function formatData($columns) {
        $arr = [];

        foreach ($columns as $column) {
            $name = $column->getName();
            $value = $column->getValue();

            $value = $this->changeFieldValueType($name, $value);

            $arr[$name] = $value;
        }
        // var_dump($arr);
        return $arr;
    }

    public function insertOrUpdate(array $data, $database, $table) {
        $params = [
            'index' => $database . '_' . $table . '_' . $data['category_id'],
            'id' => $data['id'],
            'type' => '_doc',
            'body' => $data
        ];

        // echo 'input:', PHP_EOL, json_encode($params), PHP_EOL;
        $this->log->info('input:', $params);
        
        try {
            $res = $this->getEs()->index($params);
        } catch (\Exception $t) {
            // echo 'error: ';
            // var_dump($t->getMessage());
            $this->log->error('insert or update exception: ' . $t->getMessage());
            return ;
        }
        
        // echo 'result: ', $res['result'], PHP_EOL;
        $this->log->info('result: ' . $res['result']);
    }

    public function delete(array $data, $database, $table) {
        $params = [
            'index' => $database . '_' .$table . '_' . $data['category_id'],
            'type' => '_doc',
            'id' => $data['id']
        ];

        // echo 'input:', json_encode($params), PHP_EOL;
        $this->log->info('input:' . json_encode($params));
        
        try {
            $res = $this->getEs()->delete($params);
        } catch (\Exception $t) {
            // echo 'error: ';
            // var_dump($t->getMessage());
            $this->log->error('delete exception: ' . $t->getMessage());
            return ;
        }
        
        // echo 'result: ', $res['result'] . PHP_EOL;
        $this->log->info('result: ' . $res['result']);
    }
}
